import React, {  useRef,useEffect ,useState,forwardRef,useImperativeHandle,FC} from 'react'
import { Button, Input,Tree,Form,Spin,Modal,Menu, Dropdown, message } from 'antd'
import MyTable from '@/components/common/table'
// import { isAuthorized } from '@/assets/js/publicFunc'
import MySelect from '@/components/common/mySelect'
import User from '@/api/user'
import { formItemLayout } from '@/config/layout'
import './index.less';
import UserOrg from '@/api/userorg'
import { TreeNode } from 'rc-tree'
import MyDefineSelect from '@/components/common/myDefineSelect'
import ChooseUserGroupCom from '@/components/common/chooseGroup'
import {
  SmallDashOutlined
} from '@ant-design/icons';
let hasFirstOrgId = false;
let firstOrgId = '';
const UserList: FC = () => {
  const tableRef: RefType = useRef()
   //菜单树
   const [treeData,setTreeData] = useState<any[]>([]);
   //部门id
   const [orgid,setorgid] = useState('');
   //是否加载完部门树
   const [pageshow,setPageShow] = useState(false);
   const userEdit: RefType = useRef()
   const userOrgEdit: RefType = useRef()
  // 添加
  const add = () => {
    userEdit.current.init('',orgid);
  }
   // 修改
   const edit = (record:any) => {
    userEdit.current.init(record.staffId,orgid);
  }
  // 删除
  const del = (record:any) => {
    Modal.confirm({
      title: '确认删除？',
      
      onOk() {
        User.userDel({
          userid:record.staffId,
         
        }).then(()=>{
          tableRef.current.update();
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  // 新增按钮
  const AddBtn = () => (
    <Button className="fr" onClick={add} type="primary">
      新增用户
    </Button>
  )

  const onSelectRow = (rowKeys: string[]) => {
    console.log('rowKeys: ', rowKeys)
  }
  const columns = [
    {
      title: '用户名',
      dataIndex: 'staffName',
      key:'staffName'
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key:'gender',
      render:(txt)=>{
        let genderObj = {
          "2":"女",
          "1":"男",
          "3":"未知"
        }
        return genderObj[txt];
      }
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key:'phone'
    },
    {
      title: '工号',
      dataIndex: 'staffCode',
      key:'staffCode',
    }, 
    // {
    //   title: '邮箱',
    //   dataIndex: 'email',
    //   key:'email'
    // },
    {
      title: '操作',
      dataIndex: 'operations',
      align: 'center',
      render: (txt,record) => (
        <>
          <Button className="btn" onClick={()=>edit(record)} size="small">编辑</Button>
          <Button className="btn" onClick={()=>del(record)} size="small">删除</Button>
        </>
      )
    }
  ]
  useEffect(()=>{
    if(tableRef){
      tableRef.current&&tableRef.current.update();
    }
    
  },[orgid])
  const onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
    if(selectedKeys.length>0){
      setorgid(selectedKeys[0]);
    }
  };
   // 搜索栏配置项
   const searchConfigList = [
    {
      key: 'name',
      slot: <Input placeholder="请输入关键字" allowClear />,
      rules: [],
      initialValue: ''
    },
  ]
  return (
    <>
      <div className="user-list">
      <AddBtn />
        <MyTable 
          apiFun={User.getList}
          expendParams={{'orgid':orgid}}
          columns={columns}
          ref={tableRef} 
          searchConfigList = {searchConfigList}
          extraProps={{ results: 10 }}
        />
      </div>
      <UserEditCom ref={userEdit} callback={()=>{
        tableRef.current.update();
      }}/>
    </>
  )
}
export default UserList

 
//新建/修改用户
const UserEdit = (props,refs) => {
  const ChooseUserGroupRef: RefType = useRef()
  const [loading, setLoading] = useState<boolean>(false)
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
   //用户id
   const [userid,setId] = useState('');
   //部门id
   const [orgId,setorgId] = useState('');
   const [orgName,setOrgName] = useState('');
   //form
   const [form] = Form.useForm()
   const { setFieldsValue, resetFields } = form
   useImperativeHandle(refs, () => ({
    init: (id,orgid) => {
      setId(id);
      if(id){
        getDetail(id);
      }else{
        resetFields();
        setorgId('');
        setOrgName('');
        showModal();
      }
     
    }
  }))
  //获取详情
  const getDetail = (id)=>{
    User.userDetail({
      'staffid':id
    }).then((res)=>{
      console.log(res);
      setFieldsValue({
        ...res.data,
        
      });
      let dept  = res.data['dept']?res.data['dept']:{};
      setorgId(dept['deptId']);
      setOrgName(dept['deptName']);
      showModal();
    })
  }

  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };
  //确定
  const handleOk = () => {
    if(orgId==''){
      message.error('请选择所属组织');
      return;
    }
    form.validateFields().then((vals) => {
      const Obj = form.getFieldsValue()
      setLoading(true)

      const fn = userid===''?User.userAdd:User.userEdit;
      const params = {
        ...Obj,
        ...userid===''?{}:{'staffId':userid},
        ...{
          deptId:orgId
        }
      };
      fn(params).then((res)=>{
        handleCancel();
      })
    }).catch(info => {
      
    })
  };
  const setnowCheckedGroup = (OBJ)=>{
    setorgId(OBJ['id']);
    setOrgName(OBJ['name']);
    
  }
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setId('');
    setorgId('');
    setOrgName('');
    setLoading(false);
    props.callback&&props.callback();
  };

  return <Modal 
    title={userid===''?'新增用户':'编辑用户'}
    visible={isModalVisible} 
    onOk={handleOk} 
    onCancel={handleCancel}
    maskClosable={false}
    width={600}
    >

    <Spin spinning={loading}>
      <Form {...formItemLayout} form={form}>
        <Form.Item
          label="用户名"
          name="staffName"
          rules={[
            {
              required: true,
              message: '请输入用户名'
            }
          ]}
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>
        <Form.Item
          label="邮箱"
          name="email"
        >
          <Input placeholder="请输入邮箱" />
        </Form.Item>
        <Form.Item
          label="性别"
          name="gender"
        >
          <MyDefineSelect 
            url="/dm/api/sys/dict/selectDictLabel"
            params={{'dictindex':"sex"}}
            namekey="optionlabel"
            idkey="optionvalue"
            requestMethod="post"
            formatIdKey={(key)=>{return key}}
          />
        </Form.Item>
        <Form.Item
          label="身份证号"
          name="idCode"
          rules={[
            {
              required: true,
              message: '请输入身份证号'
            }
          ]}
        >
          <Input placeholder="请输入身份证号" />
        </Form.Item>
       
        <Form.Item
          label="主数据编码"
          name="mdmCode"
        >
          <Input placeholder="请输入主数据编码" />
        </Form.Item>
        <Form.Item
          label="手机号"
          name="phone"
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item
          label="职介ID"
          name="rankId"
        >
          <Input placeholder="请输入职介ID" />
        </Form.Item>
        <Form.Item
          label="工号"
          name="staffCode"
        >
          <Input placeholder="请输入工号" />
        </Form.Item>
        <Form.Item 
          label="所属组织" 
          name="orgName"
          className="chooseUserWrap"
          >
          <div className="" onClick={()=>{
            ChooseUserGroupRef.current.init();
          }}>
             <Input value={orgName}/>
          </div>
        </Form.Item>
        <Form.Item
          label="岗位"
          name="titleId"
        >
          <MyDefineSelect 
            url="/dm/api/sys/dict/selectDictLabel"
            params={{'dictindex':"title"}}
            namekey="optionlabel"
            idkey="optionvalue"
            requestMethod="post"
            formatIdKey={(key)=>{return key}}
          />
        </Form.Item>

      </Form>
    </Spin>
    <ChooseUserGroupCom ref={ChooseUserGroupRef} callback={(callback_v)=>{
          let obj = callback_v[0];
          setnowCheckedGroup(obj)
      }}/>
  </Modal>
}



const UserEditCom = forwardRef(UserEdit);





//新建/修改部门
const UserOrgEdit = (props,refs) => {
  const [loading, setLoading] = useState<boolean>(false)
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
   //部门id
   const [orgId,setorgId] = useState('');
   //form
   const [form] = Form.useForm()
   const [type,settype] = useState(1);
   const [sub,setsub] = useState('');
   const { setFieldsValue, resetFields } = form
   useImperativeHandle(refs, () => ({
    init: (id,record,q_type,q_sub) => {
      console.log(id)
      console.log(record);
      settype(q_type);
      setorgId(id);
      setsub(q_sub)
      if(id){
        setFieldsValue(record)
       
      }else{
        resetFields();
        if(q_type==1){
          setFieldsValue({
            supDept:record.deptId
          })
        }
      }
      showModal();
     
    }
  }))
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };
  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {
      const Obj = form.getFieldsValue()
      setLoading(true)
      let titlename = type == 1?'部门':'公司'

      const fn = orgId===''?(type==1?UserOrg.addDept:UserOrg.addCompany):(type==1?UserOrg.updateDept:UserOrg.updateCompany);
      const params = {
        ...Obj
      };

      if(sub){
        if(type==1){
          params['corpId'] = sub;
          // params['supDept'] = sub;
        }else{
          params['supCorpId'] = sub;
        }
      }
      console.log(params);
      fn(params).then((res)=>{
        handleCancel();
      })
    }).catch(info => {
      
    })
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setLoading(false);
    setorgId('');
    props.callback&&props.callback();
  };
  let titlename = type == 1?'部门':'公司'
  return <Modal 
    title={orgId===''?'新增'+titlename:'编辑'+titlename}
    visible={isModalVisible} 
    onOk={handleOk} 
    onCancel={handleCancel}
    width={600}
    >

    <Spin spinning={loading}>
      <Form {...formItemLayout} form={form}>
        {
          type == 1?<>
              <Form.Item
                  label="部门id"
                  name="deptId"
                  style={{display:'none'}}
                >
                  <Input />
              </Form.Item>  

              <Form.Item
                  label="父部门id"
                  name="supDept"
                  style={{display:'none'}}
                >
                  <Input />
              </Form.Item>  
              <Form.Item
                  label="公司id"
                  name="corpId"
                  style={{display:'none'}}
                >
                  <Input />
              </Form.Item>  
              <Form.Item
                label="组织名称"
                name="deptName"
                rules={[
                  {
                    required: true,
                    message: '请输入组织名称'
                  }
                ]}
              >
                <Input placeholder="请输入组织名称" />
              </Form.Item>
              <Form.Item
                label="组织编码"
                name="orgCode"
                rules={[
                  {
                    required: true,
                    message: '请输入组织编码'
                  }
                ]}
              >
                <Input  placeholder="请输入组织编码" />
              </Form.Item>
              <Form.Item
                label="组织简称"
                name="deptShortName"
                rules={[
                  {
                    required: true,
                    message: '请输入组织简称'
                  }
                ]}
              >
                <Input placeholder="请输入组织简称" />
              </Form.Item>
              <Form.Item
                label="组织类型"
                name="deptTypeId"
                rules={[
                  {
                    required: true,
                    message: '请选择组织类型'
                  }
                ]}
              >
                <MyDefineSelect 
                  url="/dm/api/sys/dict/selectDictLabel"
                  params={{'dictindex':"deptType"}}
                  namekey="optionlabel"
                  idkey="optionvalue"
                  requestMethod="post"
                />
              </Form.Item>
              <Form.Item
                label="主数据编码"
                name="mdmCode"
                rules={[
                  {
                    required: true,
                    message: '请输入主数据编码'
                  }
                ]}
              >
                <Input placeholder="请输入主数据编码" />
            </Form.Item>
              <Form.Item
                label="上级组织"
                name="parentOrgCode"
                style={{display:'none'}}
              >
                
              </Form.Item>
          </>:<>
            <Form.Item
                label="公司id"
                name="corpId"
                style={{display:'none'}}
              >
                
            </Form.Item>  
            <Form.Item
                label="公司名称"
                name="corpName"
                rules={[
                  {
                    required: true,
                    message: '请输入公司名称'
                  }
                ]}
              >
                <Input placeholder="请输入公司名称" />
            </Form.Item>
            <Form.Item
                label="公司简称"
                name="corpShortName"
                rules={[
                  {
                    required: true,
                    message: '请输入公司简称'
                  }
                ]}
              >
                <Input placeholder="请输入公司简称" />
            </Form.Item>
            <Form.Item
                label="法人代表"
                name="corpRep"
                rules={[
                  {
                    required: true,
                    message: '请输入法人代表'
                  }
                ]}
              >
                <Input placeholder="请输入法人代表" />
            </Form.Item>
            <Form.Item
                label="公司类型"
                name="corpTypeId"
                rules={[
                  {
                    required: true,
                    message: '请选择公司类型'
                  }
                ]}
              >
                <MyDefineSelect 
                  url="/dm/api/sys/dict/selectDictLabel"
                  params={{'dictindex':"corpTypeId"}}
                  namekey="optionlabel"
                  idkey="optionvalue"
                  requestMethod="post"
                />
            </Form.Item>
            <Form.Item
                label="参控股方式"
                name="holdingMode"
                rules={[
                  {
                    required: true,
                    message: '请输入参控股方式'
                  }
                ]}
              >
                <Input placeholder="请输入参控股方式" />
            </Form.Item>
            <Form.Item
                label="营业执照号"
                name="licenseNo"
                rules={[
                  {
                    required: true,
                    message: '请输入营业执照号'
                  }
                ]}
              >
                <Input placeholder="请输入营业执照号" />
            </Form.Item>
            <Form.Item
                label="主数据编码"
                name="mdmCode"
                rules={[
                  {
                    required: true,
                    message: '请输入主数据编码'
                  }
                ]}
              >
                <Input placeholder="请输入主数据编码" />
            </Form.Item>
          </>
        }
        
        
      </Form>
    </Spin>
     
  </Modal>
}



const UserOrgCom = forwardRef(UserOrgEdit);

export {
  UserOrgCom
}